<?php

namespace App\Models;

use CodeIgniter\Model;

class AttachmentModel extends Model
{
    public $tablename;

    public function __construct(...$param)
    {
        parent::__construct();
        $this->tablename = 'attachment';
    }
    //新增和编辑全部数据时验证
    private function _validate($data, $id = 0)
    {
        if (!$data) {
            return ams_rt(1, '参数不全');
        }
        $data = esc($data);
        if (!$data['filename']) {
            return ams_rt(1, '文件名错误');
        } elseif (!$data['filename2']) {
            return ams_rt(1, '新文件名不存在');
        } elseif (!$data['attachment']) {
            return ams_rt(1, '文件不存在');
        }
        return ams_rt(0, 'ok');
    }

    public function add($data)
    {
        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }
        $this->db->table($this->tablename)->insert($data);
        $id = $this->db->insertID();
        if ($id) {
            return ams_rt(0, '操作成功', $id);
        }
        return ams_rt(1, '操作失败', array_merge($data));
    }

    public function edit($id, $data)
    {
        if (!$id) {
            return ams_rt(1, '参数错误');
        }
        $rt = $this->_validate($data);
        if ($rt['code']) {
            return $rt;
        }

        $idata1 = [
            'title' => $data['title'],
            'catid' => intval($data['catid']),
            'price' => isset($data['price']) ? abs($data['price']) : 0,
            'inputtime' => isset($data['inputtime']) && $data['inputtime'] ? strtotime($data['inputtime']) : time(),
            'updatetime' => isset($data['updatetime']) && $data['updatetime'] ? strtotime($data['updatetime']) : time(),
            'keywords' => isset($data['keywords']) ? $data['keywords'] : '',
            'hits' => isset($data['hits']) ? intval($data['hits']) : 0,
            'description' => isset($data['description']) ? $data['description'] : '',
            'coverimg' => isset($data['coverimg']) ? intval($data['coverimg']) : 0,
            'pictures' => isset($data['pictures']) ? $data['pictures'] : '',
            'status' => isset($data['status']),
        ];

        $flag = $this->db->table($this->tablename)->where('id', $id)->update($idata1);
        if ($flag) {
            $idata2 = [
                'id' => $id,
                'content' => $data['content'],
            ];
            $flag = $this->db->table($this->tablename . '_data')->where('id', $id)->replace($idata2);
            if (!$flag) {
                return ams_rt(1, '操作失败', array_merge($idata1, $idata2));
            }
            return ams_rt(0, '操作成功', $id);
        }
        return ams_rt(1, '操作失败', array_merge($idata1, $idata2));
    }

    public function get($id)
    {
        if (!$id) {
            return ams_rt(1, '参数错误');
        }
        $row = $this->db->table($this->tablename)->join($this->tablename . '_data', $this->tablename . '_data.id = ' . $this->tablename . '.id')->where($this->tablename . '.id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在', []);
        }
        return ams_rt(0, 'ok', $row);
    }

    public function del($id)
    {
        $id = intval($id);
        if (!$id) {
            return ams_rt(1, '参数错误');
        }
        //数据归属
        $row = $this->db->table($this->tablename)->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在');
        }
        $this->db->table($this->tablename)->where('id', $id)->delete();
        //删除文件
        @unlink(WEBPATH . $row['attachment']);
        return ams_rt(0, '操作成功');
    }

    // 分页
    public function limit_page($page = 0, $size = 10, $total = 0, $param = [])
    {

        $page = max(1, (int) $page);
        $total = (int) $total;

        unset($param['page']);
        if ($param) {
            $param = esc($param);
        }

        if ($size > 0 && !$total) {
            $select = $this->db->table($this->tablename)->select('count(*) as total');
            $param = $this->_limit_page_where($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->tablename);
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->tablename);
        $order = isset($param['order']) ? esc($param['order']) : '';
        $param = $this->_limit_page_where($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy($order)->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->tablename);
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        $param['order'] = $order;
        $param['total'] = $total;

        return [$data, $total, $param];

    }

    /**
     * 条件查询
     *
     * @param    object    $select    查询对象
     * @param    intval    $where    是否搜索
     * @return    intval
     */
    protected function _limit_page_where(&$select, $param)
    {

        // 条件搜索
        if ($param) {

            // 关键字 + 自定义字段搜索
            if (isset($param['keyword']) && $param['keyword'] != '') {

                if ($param['id']) {
                    $select->where('id', (int) $$param['id']);
                } elseif ($param['ids']) {
                    $select->whereIn('id', $param['ids']);
                }

                if (isset($param['catname']) && $param['catname']) {
                    $select->where('catid IN (select id from `' . $this->dbprefix('article_category') . '` where `name` like "%' . $param['catname'] . '%")');
                }

                if (isset($param['title'])) {
                    $select->like('title', urldecode($param['title']));
                }
            }
            // 时间搜索
            if (isset($param['sdate']) && $param['sdate']) {
                $select->where('addtime BETWEEN ' . max((int) strtotime($param['sdate'] . ' 00:00:00'), 1) . ' AND ' . ($param['edate'] ? (int) strtotime($param['edate'] . ' 23:59:59') : SITE_TIME));
            } elseif (isset($param['edate']) && $param['edate']) {
                $select->where('addtime BETWEEN 1 AND ' . (int) strtotime($param['edate'] . ' 23:59:59'));
            }
            // 栏目查询
            // if (isset($param['catid']) && $param['catid']) {
            //     $cat['child'] ? $select->whereIn('catid', explode(',', $cat['childids'])) : $select->where('catid', (int)$param['catid']);
            // }
        }
        return $param;
    }

}
